package com._21cn.cms.resource.web.servlet;

import com._21cn.cms.common.Constants;
import com._21cn.cms.resource.entity.Picture;
import com._21cn.cms.resource.utils.PictureManager;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Servlet implementation class PictureFetchServlet
 */
public class PictureFetchServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final Logger log = LoggerFactory.getLogger(PictureFetchServlet.class);

    private PictureManager manager;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf8");
        response.setCharacterEncoding("utf8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String urlStr = request.getParameter("url");
        String title = request.getParameter("title");
        String memo = request.getParameter("memo");
        Integer status = Constants.STATUS_ENABLE;
        if (StringUtils.isEmpty(urlStr)) {
            log.debug("url is empty!");
            return;
        }
        // 多个地址之间用“,21cn.com,”分
        String[] urls = urlStr.split(",21cn.com,");
        Set<String> urlList = new HashSet<String>();
        for (String url : urls) {
            urlList.add(url);
        }
        Map<String, Picture> result = manager.fetchPictureFromUrls(urlList, title, memo, null, status);
        out.println(JSON.toJSONString(result, true));
        out.flush();
        out.close();

    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext());
        manager = (PictureManager) wac.getBean("pictureManager");

    }

}
